// src/pages/search/index.tsx
import styles from "@pages/search/styles/styles.module.less";
import Back from "@shared/back";
import GeekIcon from "@shared/geekIcon";
import Suggestion from "@pages/search/widgets/suggestion";
import React, { useEffect, useMemo, useState } from "react";
import { useTypedDispatch } from "@store/index";
import { useLazyRequestSuggestionQuery, searchApiService } from "@service/search";
import { useDebounce } from "use-debounce";
import SearchKey from "@pages/search/widgets/searchKey";
import { useNavigate } from "react-router-dom";
import { addKey } from "@slice/searchKey";
export default function Search() {
   // 获取用于实现页面跳转的方法
   const navigate = useNavigate();
   // 用于记录用户在文本框中输入的搜索关键字
   const [key, setKey] = useState("");
   // 用于发送请求获取联想建议关键字列表
   const [requestSuggestion, { data: suggestion }] = useLazyRequestSuggestionQuery();
   // 获取 dispatch 方法
   const dispatch = useTypedDispatch();
   // 得到一个被防抖之后的值 (在一定时间内, 多次触发同一个事件, 只执行最后一次操作)
   const [debounceValue] = useDebounce(key, 1000);
 
   // 监听防抖值的变化
   useEffect(() => {
     // 如果关键字的长度大于 0
     if (debounceValue.trim().length > 0) {
       // 发送请求
       requestSuggestion(debounceValue);
     } else {
       // 否则清空已有联想值列表
       dispatch(searchApiService.util.resetApiState());
     }
   }, [debounceValue, dispatch, requestSuggestion]);
 
   // 布尔类型, 联想关键词列表是否存在
   const hasSuggestion = useMemo<boolean>(() => {
     if (typeof suggestion === "undefined") return false;
     return suggestion.data.options.filter((item:any) => item).length > 0;
   }, [suggestion]);
   
   // 创建用于匹配搜索关键字的正则对象
   const reg = useMemo(() => {
     return new RegExp(debounceValue, "gi");
   }, [debounceValue]);
  return (
    <div className={styles.search_page}>
      <div className={styles.header}>
        <Back />
        <div className={styles.input}>
          <GeekIcon type={"iconbtn_search"} />
          <input
            value={key}
            onChange={(event) => setKey(event.target.value)}
            type="search"
            placeholder={"请输入关键字搜索"}
          />
        </div>
        <span
      onClick={() => {
        if (debounceValue.trim().length > 0) {
          dispatch(addKey({ name: debounceValue }));
          navigate(`/result/${debounceValue}`);
        }
      }}
    >
      搜索
    </span>
      </div>
      {hasSuggestion && (
        <Suggestion
          suggestions={suggestion!.data.options
            .filter((item:any) => item)
            .map((item:any) => ({
              origin: item,
              name: item.replace(reg, (str:any) => `<span>${str}</span>`),
            }))}
        />
      )}
      {!hasSuggestion && <SearchKey />}
    </div>
  );
}